package org.southyin.dao;

import org.southyin.model.Classes;
import org.southyin.model.Stu;
import org.southyin.utils.DBUtils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StuDaoImpl implements StuDao {
    @Override
    public List<Stu> getStuInfos() {
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Stu> list = new ArrayList<>();
        try {
            ps = DBUtils.conn.prepareStatement("select s.id,username,gender,joinTime,mobile,cid,c.id cid2,cname,createTime\n" +
                    "from stu s\n" +
                    "join classes c\n" +
                    "on s.cid = c.id");
            rs = ps.executeQuery();
            while (rs.next()) {
                Stu s = new Stu();
                s.setId(rs.getLong("id"));
                s.setUsername(rs.getString("username"));
                s.setGender(rs.getBoolean("gender"));
                s.setJoinTime(rs.getTimestamp("joinTime"));
                s.setMobile(rs.getString("mobile"));
                s.setCid(rs.getLong("cid"));

                Classes c = new Classes();
                c.setId(rs.getLong("cid2"));
                c.setCname(rs.getString("cname"));
                c.setCreateTime(rs.getDate("createTime"));
                s.setClasses(c);

                list.add(s);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.getInstance().close(rs);
            DBUtils.getInstance().close(ps);
        }
        return list;
    }
}
